package cn.zhentao.controller;

import cn.zhentao.utils.AliyunOcrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * OCR图片识别控制器
 * 使用阿里云OCR API进行图片文字识别
 *
 * @author zhentao
 */
@RestController
@RequestMapping("/ocr")
@Api(tags = "OCR图片识别")
@Slf4j
public class OcrController {

    @Autowired
    private AliyunOcrUtil aliyunOcrUtil;
    
    @PostMapping("/general/url")
    @ApiOperation(value = "通用文字识别（URL）", notes = "通过图片URL进行文字识别")
    public Map<String, Object> recognizeGeneralTextByUrl(
            @ApiParam(value = "图片URL", required = true) @RequestParam String imageUrl) {

        long startTime = System.currentTimeMillis();

        try {
            log.info("🔤 开始通用文字识别 - URL: {}", imageUrl);

            // 参数验证
            if (imageUrl == null || imageUrl.trim().isEmpty()) {
                return buildErrorResponse("图片URL不能为空", "PARAM_ERROR");
            }

            // 调用OCR服务
            String ocrResult = aliyunOcrUtil.recognizeTextByUrl(imageUrl.trim());

            return buildSuccessResponse("OCR识别成功", Map.of(
                "ocrResult", ocrResult,
                "imageUrl", imageUrl.trim(),
                "processingTime", System.currentTimeMillis() - startTime
            ));

        } catch (Exception e) {
            log.error("❌ OCR识别失败 - URL: {}, 错误: {}", imageUrl, e.getMessage(), e);
            return buildErrorResponse("OCR识别失败: " + e.getMessage(), "OCR_ERROR");
        }
    }

    @PostMapping("/general/file")
    @ApiOperation(value = "通用文字识别（文件上传）", notes = "上传图片文件进行文字识别")
    public Map<String, Object> recognizeGeneralTextByFile(
            @ApiParam(value = "图片文件", required = true) @RequestParam("file") MultipartFile file) {

        long startTime = System.currentTimeMillis();

        try {
            log.info("🔤 开始通用文字识别 - 文件: {}, 大小: {}KB",
                file.getOriginalFilename(), file.getSize() / 1024);

            // 参数验证
            if (file == null || file.isEmpty()) {
                return buildErrorResponse("图片文件不能为空", "PARAM_ERROR");
            }

            // 文件大小检查（10MB限制）
            if (file.getSize() > 10 * 1024 * 1024) {
                return buildErrorResponse("文件大小不能超过10MB", "FILE_TOO_LARGE");
            }

            // 调用OCR服务
            String ocrResult = aliyunOcrUtil.recognizeTextByStream(
                file.getInputStream(), file.getOriginalFilename());

            return buildSuccessResponse("OCR识别成功", Map.of(
                "ocrResult", ocrResult,
                "fileName", file.getOriginalFilename(),
                "fileSize", file.getSize(),
                "processingTime", System.currentTimeMillis() - startTime
            ));

        } catch (IOException e) {
            log.error("❌ 文件读取失败 - 文件: {}, 错误: {}", file.getOriginalFilename(), e.getMessage(), e);
            return buildErrorResponse("文件读取失败: " + e.getMessage(), "FILE_READ_ERROR");
        } catch (Exception e) {
            log.error("❌ OCR识别失败 - 文件: {}, 错误: {}", file.getOriginalFilename(), e.getMessage(), e);
            return buildErrorResponse("OCR识别失败: " + e.getMessage(), "OCR_ERROR");
        }
    }

    @PostMapping("/idcard/url")
    @ApiOperation(value = "身份证识别（URL）", notes = "通过图片URL进行身份证信息识别")
    public Map<String, Object> recognizeIdCardByUrl(
            @ApiParam(value = "图片URL", required = true) @RequestParam String imageUrl,
            @ApiParam(value = "正反面标识", required = false) @RequestParam(required = false) String side) {

        long startTime = System.currentTimeMillis();

        try {
            log.info("🆔 开始身份证识别 - URL: {}, 正反面: {}", imageUrl, side);

            // 参数验证
            if (imageUrl == null || imageUrl.trim().isEmpty()) {
                return buildErrorResponse("图片URL不能为空", "PARAM_ERROR");
            }

            // 调用OCR服务
            String ocrResult = aliyunOcrUtil.recognizeIdCardByUrl(imageUrl.trim());

            return buildSuccessResponse("身份证识别成功", Map.of(
                "ocrResult", ocrResult,
                "imageUrl", imageUrl.trim(),
                "side", side != null ? side : "unknown",
                "processingTime", System.currentTimeMillis() - startTime
            ));

        } catch (Exception e) {
            log.error("❌ 身份证识别失败 - URL: {}, 错误: {}", imageUrl, e.getMessage(), e);
            return buildErrorResponse("身份证识别失败: " + e.getMessage(), "IDCARD_OCR_ERROR");
        }
    }

    @PostMapping("/idcard/file")
    @ApiOperation(value = "身份证识别（文件上传）", notes = "上传身份证图片文件进行信息识别")
    public Map<String, Object> recognizeIdCardByFile(
            @ApiParam(value = "身份证图片文件", required = true) @RequestParam("file") MultipartFile file,
            @ApiParam(value = "正反面标识", required = false) @RequestParam(required = false) String side) {

        long startTime = System.currentTimeMillis();

        try {
            log.info("🆔 开始身份证识别 - 文件: {}, 正反面: {}", file.getOriginalFilename(), side);

            // 参数验证
            if (file == null || file.isEmpty()) {
                return buildErrorResponse("身份证图片文件不能为空", "PARAM_ERROR");
            }

            // 文件大小检查
            if (file.getSize() > 10 * 1024 * 1024) {
                return buildErrorResponse("文件大小不能超过10MB", "FILE_TOO_LARGE");
            }

            // 调用OCR服务
            String ocrResult = aliyunOcrUtil.recognizeIdCardByStream(
                file.getInputStream(), file.getOriginalFilename());

            return buildSuccessResponse("身份证识别成功", Map.of(
                "ocrResult", ocrResult,
                "fileName", file.getOriginalFilename(),
                "fileSize", file.getSize(),
                "side", side != null ? side : "unknown",
                "processingTime", System.currentTimeMillis() - startTime
            ));

        } catch (IOException e) {
            log.error("❌ 文件读取失败 - 文件: {}, 错误: {}", file.getOriginalFilename(), e.getMessage(), e);
            return buildErrorResponse("文件读取失败: " + e.getMessage(), "FILE_READ_ERROR");
        } catch (Exception e) {
            log.error("❌ 身份证识别失败 - 文件: {}, 错误: {}", file.getOriginalFilename(), e.getMessage(), e);
            return buildErrorResponse("身份证识别失败: " + e.getMessage(), "IDCARD_OCR_ERROR");
        }
    }

    // ==================== 统一响应构建方法 ====================

    /**
     * 构建成功响应
     */
    private Map<String, Object> buildSuccessResponse(String message, Object data) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", message);
        response.put("data", data);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }

    /**
     * 构建错误响应
     */
    private Map<String, Object> buildErrorResponse(String message, String errorCode) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        response.put("errorCode", errorCode);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }

}
